#include <stdio.h>
#include <sched.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "motor_pwm.h"

static int duty_cycle_fd;
static char buf[20];

void init_pwm()
{
    //导出PWM0
    int export_fd = open("/sys/class/pwm/pwmchip0/export", O_WRONLY);
    if(export_fd < 0)
    {
        perror("open error");
        exit(0);
    }
    write(export_fd, "0", 1);
    close(export_fd);
    //设置PWM周期
    int period_fd = open("/sys/class/pwm/pwmchip0/pwm0/period", O_WRONLY);
    sprintf(buf, "%d", PWM_PERIOD);
    write(period_fd, buf, strlen(buf));
    close(period_fd);
    //设置占空比
    duty_cycle_fd = open("/sys/class/pwm/pwmchip0/pwm0/duty_cycle", O_WRONLY);
    write(duty_cycle_fd, "0", 1);
    //使能PWM输出
    int enable_fd = open("/sys/class/pwm/pwmchip0/pwm0/enable", O_WRONLY);
    write(enable_fd, "1", 1);
    close(enable_fd);
}

//设置PWM输出，参数0.0到100.0
void set_pwm_output(double duty_cycle)
{
    if (duty_cycle < 0.0)
        duty_cycle = 0.0;
    else if (duty_cycle > 100.0)
        duty_cycle = 100.0;
    int i = duty_cycle * PWM_PERIOD / 100;
    sprintf(buf, "%d", i);
    write(duty_cycle_fd, buf, strlen(buf));
}

